import base64
import hmac
import urllib

from django.shortcuts import render, redirect
# 导包
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
# 导入类视图
from django.views import View

from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

import requests

# 导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

# 导入原生sql模块
from django.db import connection

import jwt

# 导入redis数据库
import redis

# 导入时间模块
import time

# 导入公共目录变量
from mydjango.settings import BASE_DIR

# 导包
from django.db.models import Q, F

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

# 导入序列化对象
from myapp.myser import UserSer

import redis

host = '127.0.0.1'
port = 6379

r = redis.Redis(host=host, port=port)


class KaoshiRegister(APIView):

    def get(self, request):
        username = request.GET.get('username')
        password = request.GET.get('password')

        user = User.objects.filter(username=username).first()

        if user:
            res = {}
            res['code'] = 405
            res['message'] = '该用户已注册'
            return Response(res)

        u = User(username=username, password=password, type=0, img='1')
        u.save()
        res = {}
        res['code'] = 200
        res['message'] = '注册成功'
        return Response(res)


class KaoshiLogin(APIView):
    def get(self, request):
        username = request.GET.get('username')
        password = request.GET.get('password')

        user = User.objects.filter(username=username, password=password).first()

        if user:
            res = {}
            res['code'] = 200
            res['message'] = '登录成功'
            return Response(res)
        else:
            res = {}
            res['code'] = 405
            res['message'] = '用户名或密码错误'
            return Response(res)


class KaoshiDingDing_back(APIView):

    def get(self, request):
        code = request.GET.get('code')

        t = time.time()
        appSecret = "eMd7zuSSTfsXcbBg2SSBIODnZlDSwv8kWq_RStPudmEDTyEesp-U3UJoLzPOAnmB"
        timestamp = str(int(round(t * 1000)))
        signature = base64.b64encode(
            hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=hashlib.sha256).digest())
        request_url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=dingoasyyehyz5u1fzgmcv&timestamp=" + timestamp + "&signature=" + urllib.parse.quote(
            signature.decode('utf-8'))
        headers = {'Content-Type': 'application/json'}
        res = requests.post(url=request_url, data=json.dumps({'tmp_auth_code': code}), headers=headers)
        data = res.json()['user_info']['nick']
        return Response({'data':data})
